package com.fingard.dsp.bank.directbank.cqcb01;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.directbank.cqcb01.CQCB01Base;
import com.fingard.dsp.bank.directbank.cqcb01.CQCB01Header;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class CQCB01Transaction extends CQCB01Base implements ITransaction {

	//采用流处理方式
	//1、循环调用readRecord()读取一个请求明细，然后写入发银行的XML对象
	//2、发银行
	//3、循环调用XmlTextReader.read()读取一个银行返回节点，赋值返回ATS的明细对象，
	//   然后调用writeRetDetail()，写入返回ATS的明细
	public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception{
		//历史明细查询返回ATS的对象
		RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
		String tmpRespCode = "";
		String tmpRespInfo = "";
		String bodycontent = "";
		retAts.writeStart();//写返回ATS的统一头部信息
		try {
			CQCB01Header tmpBankHeader = new CQCB01Header();
			tmpBankHeader.transCode = "4404";

			//tmpClndrStepTo.get(Calendar.MONTH) MONTH是从0开始编的，意味着0是1月，11是12月
			Calendar tmpCalendarFrom = Calendar.getInstance();
			tmpCalendarFrom.setTime(p_req7516.getDateFrom());
			
			Calendar tmpCalendarTo = Calendar.getInstance();
			tmpCalendarTo.setTime(p_req7516.getDateTo());

			//发送银行之前报文主体部分送到前置机的签名端口
			String actNum = p_req7516.actNum;
			String beginDate =  Format.Date8Format.format(tmpCalendarFrom.getTime());
			String endDate = Format.Date8Format.format(tmpCalendarTo.getTime());
			bodycontent="<body><trans><AccountNo>"+actNum+"</AccountNo><BgnDate>"+beginDate+"</BgnDate><EndDate>"+endDate+"</EndDate></trans></body>";
			int length=bodycontent.getBytes().length;
			//	以下2行为签名前置服务器要求送的串，qmhead无需修改
			String qmhead="http://192.168.0.133/servlet/CQBANK.Trans HTTP/1.0\r\nAccept:image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint,application/vnd.ms-excel,application/msword, */*\r\nReferer: http://192.168.0.133/CQBANKB2E.htm\r\nAccept-Language: zh-cn\r\nContent-Type: INFOSEC_SIGN/1.0\r\nProxy-Connection: Keep-Alive\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)\r\nHost: 192.168.0.133\r\n";
			String qmlength="Content-Length:"+" "+String.valueOf(length)+"\r\n\r\n";
			//	构造的最终串
			String qm=qmhead+qmlength+bodycontent;
			String[] tmpSign = sendToBankSignXml(qm);
			if(tmpSign[0].length()==0) {
				String signature = "";
				String body = "";
				String aa = "<result>";
				int i = tmpSign[1].indexOf(aa);
				if (i != -1) {
					body = tmpSign[1].substring(i + 8, i + 9);
				}
				if (body.equals("0")) {
					String ab = "<sign>";
					String ac = "</sign>";
					int ib = tmpSign[1].indexOf(ab);
					int ic = tmpSign[1].indexOf(ac);
					//以下为最终的签名结果
					signature = tmpSign[1].substring(ib + 6, ic);
					//int tmpNowReadedCount = 0;
					boolean tmpQryNext = true;
					while (tmpQryNext && tmpRespCode.length() == 0) {//查询
						XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
						//写入通用的头部节点
						writeCommonHeader(xmlWriter, tmpBankHeader);
						xmlWriter.writeElementString("signature", signature);
						xmlWriter.writeEndElement();
						xmlWriter.writeEndDocument();
						String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
						XmlTextReader tmpBkReader;
						if (tmpStrRet[0].length() == 0) {
							StringBuilder tmpSbMsg = new StringBuilder();
							tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
							if (tmpBkReader != null) {
								String returnCode = tmpBkReader.getFirstText("/out/head/ErrorCode");
								String returnMsg = tmpBkReader.getFirstText("/out/head/ErrorMsg");
								if (isActiveRetCode(returnCode)) {
									//int tmpEachPiCount = 0;
									while (tmpBkReader.read("/out/body/Trans")) {
										//tmpEachPiCount++;
										RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
										tmpRetDetail.payCode = tmpBkReader.readedXElement.getSingleText("VoucherNo");//凭证号码待定（支付码）
										tmpRetDetail.accBal = tmpBkReader.readedXElement.getSingleText("AcctAmt");
										tmpRetDetail.recAccNum = tmpBkReader.readedXElement.getSingleText("OppAcct");
										tmpRetDetail.recAccName = tmpBkReader.readedXElement.getSingleText("OppName");
										String creditDebitFlag = tmpBkReader.readedXElement.getSingleText("TransMark");//＋，表示存入；－，表示借出 D:借 C：贷
										String tranAmount = tmpBkReader.readedXElement.getSingleText("TransAmt");
										if (creditDebitFlag != null) {
											if (creditDebitFlag.equals("-")) //表示支出
											{
												if (tranAmount.indexOf("-") >= 0) {
													tmpRetDetail.cdFlag = "2";
												} else {
													tmpRetDetail.cdFlag = "1";
												}
											} else if(creditDebitFlag.equals("+")){
												if (tranAmount.indexOf("-") >= 0) {
													tmpRetDetail.cdFlag = "1";
												} else {
													tmpRetDetail.cdFlag = "2";
												}
											}
											else{
												tmpRespCode = "-1";
												tmpRespInfo = "返回的借贷标志未知";
												retAts = new RetAtsTrans(p_req7516.reqHeader);
												retAts.writeStart();//写返回ATS的统一头部信息
												retAts.writeRespCode(tmpRespCode);
												retAts.writeRespInfo(tmpRespInfo);
												retAts.writeEnd();
												return retAts;
											}
										}
										tmpRetDetail.tranAmt = tranAmount.replace("-", "");
										String tranTime = tmpBkReader.readedXElement.getSingleText("TransTime");
										String tranDate = tmpBkReader.readedXElement.getSingleText("TransDate");
										tmpRetDetail.tranDate = tranDate.substring(0, 4) + "-" + tranDate.substring(4, 6) + "-" + tranDate.substring(6, 8);
										if (StringHelper.hasAnyChar(tranTime)) {
											tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + tranTime.substring(0, 2) + ":" + tranTime.substring(2, 4) + ":" + tranTime.substring(4, 6);
										} else {
											tmpRetDetail.tranTime = tmpRetDetail.tranDate;
										}
										tmpRetDetail.valueDate = tmpRetDetail.tranDate;//起息日没有返回就用交易日

										tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("Summary");
										tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.usage);
										if (StringHelper.isNullOrEmpty(tmpRetDetail.actNum)) {
											tmpRetDetail.actNum = p_req7516.actNum;
										}
										retAts.writeRetDetail(tmpRetDetail);
									}
									tmpQryNext = false;
								} else {
									tmpQryNext = false;
									tmpRespCode = "-1";
									tmpRespInfo = returnMsg;
									break;
								}
							} else {
								tmpQryNext = false;
								tmpRespCode = "-1";
								tmpRespInfo = tmpSbMsg.toString();
								break;
							}
						} else {
							tmpQryNext = false;
							tmpRespCode = "-1";
							tmpRespInfo = tmpStrRet[1];
							break;
						}
					}
				} else {//签名数据返回数据为空
					tmpRespCode = "-1";
					tmpRespInfo = tmpSign[1];
				}
			}
			else {
				tmpRespCode = "-1";
				tmpRespInfo = tmpSign[1];
			}
		} catch (Exception e) {
			tmpRespCode = "-1";
			tmpRespInfo = e.getMessage();
			e.printStackTrace();
		}
		if(tmpRespCode.equals("-1")){
			retAts = new RetAtsTrans(p_req7516.reqHeader);
			retAts.writeStart();//写返回ATS的统一头部信息
			retAts.writeRespCode(tmpRespCode);
			retAts.writeRespInfo(tmpRespInfo);
		}
		else if(retAts.getWrittenRdCount() == 0){
			retAts.writeRespCode("0");
			retAts.writeRespInfo("交易为空");
		}
		retAts.writeEnd();
		return retAts;
	}

	//当日明细查询调用历史明细查询方法
	public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception{
		//通用b2e0035
		Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
		tmpReq7516.actArea = p_req7515.actArea;
		tmpReq7516.actCur = p_req7515.actCur;
		tmpReq7516.actNum = p_req7515.actNum;
		String tmpStrToday = Format.Date8Format.format(new Date());
		tmpReq7516.dateFrom = tmpStrToday;
		tmpReq7516.dateTo = tmpStrToday;
		return 	d_7516_HisTrans(tmpReq7516);
	}
}
